/*
 *  Copyright (C) 2011 Alvaro Duran Tovar
 *
 *  This file is part of AFA.
 *
 *  AFA is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * CreateFilter.java
 *
 * Created on 16-mar-2011, 17:29:00
 */
package afa.view;

import afa.control.database.GetValues;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.GridBagConstraints;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 *
 * @author Alvaro Duran Tovar
 */
public class CreateFilter extends javax.swing.JFrame {

    private JTextField destiny = null;

    /**
     * Constuctor de la clase Create Filter.
     * @param destiny - Sera el destinatario del codigo generado al pulsar el boton
     */
    private CreateFilter(JTextField destiny) {
        this.destiny = destiny;
        initComponents();


        for (String s : getAvaibleFilters()) {
            jComboBox1.addItem(s);
        }
    }

    public static void createFilter(JTextField destiny){
        CreateFilter create = new CreateFilter(destiny);
        create.setVisible(true);
    }

    /**
     * Metodo que devuelve los filtros soportados.
     * Segun el filtro seleccionado se generaran elementos diferentes.
     * @return
     */
    private String[] getAvaibleFilters() {
        return new String[]{"", "plugin_names", "os", "categories", "authors", "tags"};
    }

    /**
     * Segun el parametro fn se devuelven los elementos de un tipo u otro.
     * @param fn - Filter Name.
     * @return
     */
    private String[] getValuesByFilterName(String fn) throws Exception {

        if (fn.equals("plugin_names")) {
            return getValuesByName();
        }
        if (fn.equals("os")) {
            return getValuesByOs();
        }
        if (fn.equals("categories")) {
            return getValuesByCategory();
        }
        if (fn.equals("authors")) {
            return getValuesByAuthor();
        }
        if (fn.equals("tags")) {
            return getValuesByTags();
        }

        return null;
    }

    private String[] getValuesByName() throws Exception {
        return GetValues.getValues("plugin_names");
    }

    private String[] getValuesByOs() throws Exception {
        return GetValues.getValues("os");
    }

    private String[] getValuesByCategory() throws Exception {
        return GetValues.getValues("categories");
    }

    private String[] getValuesByAuthor() throws Exception {
        return GetValues.getValues("authors");
    }

    private String[] getValuesByTags() throws Exception {
        return GetValues.getValues("tags");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jComboBox1 = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel2 = new javax.swing.JPanel();
        jCheckBox1 = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jButton1.setText("Add filter");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jPanel2.setLayout(new java.awt.GridBagLayout());
        jScrollPane1.setViewportView(jPanel2);

        jCheckBox1.setSelected(true);
        jCheckBox1.setText("Clear previous filters");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.Alignment.LEADING, 0, 308, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                    .addComponent(jCheckBox1, javax.swing.GroupLayout.Alignment.LEADING))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jCheckBox1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap())
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:
        if (jComboBox1.getSelectedIndex() == 0) {
            return;
        }

        //clear previues components
        jPanel2.removeAll();

        jPanel2.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);

        GridBagConstraints c = new GridBagConstraints();

        String[] values = new String[0];
        
        try {
            values = getValuesByFilterName(jComboBox1.getSelectedItem().toString());
        } catch (Exception ex) {
            Logger.getLogger(CreateFilter.class.getName()).log(Level.SEVERE, null, ex);
        }

        c.fill = GridBagConstraints.HORIZONTAL;
        //agrego los elementos al layout
        for (int i = 0; i < values.length; i++) {
            c.gridx = 0;
            c.gridy = i;
            c.weightx = 1.0;
            c.weighty = 0.0;
            c.anchor = GridBagConstraints.NORTH;
            jPanel2.add(new javax.swing.JCheckBox(values[i]), c);
        }
        
        //necesario para rellenar espacio al final del panel.
        //uso jpanel para que sea algo que no se vea.
        c.weighty = 1.0;
        jPanel2.add(new JPanel(), c);

        this.validate();
        this.repaint();
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        String args = "";
        String filterName = jComboBox1.getSelectedItem().toString();
        Component comps[] = jPanel2.getComponents();
        for(Component c : comps){
            //if necesario para evitar el jpanel del final
            if(!(c instanceof JCheckBox))
                continue;

            //me quedo con el nombre del los elementos seleccionados y los concateno con un ','
            //al final. OJO! siempre hay un ',' de mas, hay que quitarlo despues del for.
            JCheckBox check = (JCheckBox) c;
            if(check.isSelected())
                args += check.getText()+",";
        }

        //quitar ultimo caracter, sobra el ultimo ','
        if(args.length() > 0)
            args = args.substring(0, args.length()-1);

        //comprobar si no se ha seleccionado ningun elemento
        if(args.equals("")){
            this.dispose();
            return;
        }

        //realizar la accion con los datos anteriores
        //coloco un espacio al final por si se crean varios filtros, asi sera mas comodo a la hora
        //de parsear el string
        String text = destiny.getText();
        if(text != null && text.length() > 0 && !text.endsWith(" "))
            text += " ";

        //if checkbox == true clear previous filters
        if(jCheckBox1.isSelected())
            text = "";

        destiny.setText(text+filterName+":"+args+" ");
        destiny.postActionEvent();

        //salir
        this.dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    /*
     * no necesitamos main
     */
    /*public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new CreateFilter(null).setVisible(true);
            }
        });
    }*/
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
